<template>
  <div v-bind="$attrs" :class="props.element.className || 'loc-point-mark'" class="absolute" @click="generalEvent">
    <template v-if="!props.propValue.longDisplay && !(isVisualEditer && props.propValue.isEditerlongDisplay)">
      <template v-if="!processName">
        <template v-if="!props.propValue.isCircle">
          <img v-if="isFake" class="pmd-img-disable" src="@/assets/visual/config/drilldisable.png" />
          <img v-else-if="props.propValue.isflowmetre" class="pmd-img" src="@/assets/visual/config/flowmetre.png" />
          <img v-else-if="props.propValue.isvalve" class="pmd-img" src="@/assets/visual/config/valve.png" />
          <img v-else class="pmd-img" src="@/assets/visual/config/drillLocal.png" />
          <div v-if="setDepColor" class="ripple" />
        </template>
        <template v-else>
          <px-carousel v-if="imgArr.length > 0 && !isVisualEditer" height="44px" indicator-position="none" :autoplay="false" arrow="never">
            <px-carousel-item v-for="(iconName, index) in imgArr" :key="index" style="height: 44px">
              <img class="camera" :src="imgMap[iconName]" height="42px" width="32px" @click.stop.self="posEvent(iconName)" />
            </px-carousel-item>
          </px-carousel>
          <Ripple v-else :color="detectColor" :checkDisabled="checkDisabled" :isTriangle="props.propValue.isTriangle" :isFake="isFake" />
        </template>
      </template>
      <template v-else-if="current?.type == 'EQP' && props.propValue.isCircle && !isVisualEditer">
        <NativeTooltip>
          <template #content>
            <attrsTip
              :title="current.name"
              :code="current.showName"
              :contentList="attrsTipList"
              :groupName="replaceCharWithNewLine(props.propValue.groupName)"
              :curTreeData="flattenTreeData ? flattenTreeData[props.propValue.routerKey] : {}"
              @open-charline="openCharline"
            />
          </template>
          <div>
            <px-carousel v-if="imgArr.length > 0 && !isVisualEditer" height="44px" indicator-position="none" :autoplay="false" arrow="never">
              <px-carousel-item v-for="(iconName, index) in imgArr" :key="index" style="height: 44px">
                <img class="camera" :src="imgMap[iconName]" height="42px" width="32px" @click.stop.self="posEvent(iconName)" />
              </px-carousel-item>
            </px-carousel>
            <Ripple v-else :color="detectColor" :checkDisabled="checkDisabled" :isTriangle="props.propValue.isTriangle" />
          </div>
        </NativeTooltip>
      </template>
      <px-tooltip
        v-else-if="processName || (realImg && !isVisualEditer) || (isVisualEditer && !props.propValue.isEditerlongDisplay)"
        placement="top"
        effect="dark"
      >
        <template #content>
          <div class="flex items-center cursor-pointer" :class="{ 'set-dep-color': setDepColor }" @click="generalEvent">
            <span v-if="current?.type !== 'EQP'" :class="{ 'break-line': props.propValue.isBreakLine }">{{ processName }}</span>
            <div v-else :class="{ 'break-line': props.propValue.isBreakLine }" class="flex flex-col">
              <px-image
                v-show="realImg && !isVisualEditer"
                style="width: 200px; height: 200px"
                :src="realImg"
                :zoom-rate="1.2"
                :initial-index="4"
                :z-index="2000"
              />
              <template v-if="props.propValue.groupName">
                <span>
                  {{ replaceCharWithNewLine(props.propValue.groupName) }}
                </span>
              </template>
              <template v-else>
                <span>编号： {{ current.code }}</span>
                <span>名称： {{ current.name }}</span>
              </template>
            </div>
          </div>
        </template>
        <template v-if="!props.propValue.isCircle">
          <img v-if="isFake" class="pmd-img-disable" src="@/assets/visual/config/drilldisable.png" />
          <img v-else-if="props.propValue.isflowmetre" class="pmd-img" src="@/assets/visual/config/flowmetre.png" />
          <img v-else-if="props.propValue.isvalve" class="pmd-img" src="@/assets/visual/config/valve.png" />
          <img v-else class="pmd-img" src="@/assets/visual/config/drillLocal.png" />
          <div v-if="setDepColor" class="ripple" />
        </template>

        <template v-else>
          <px-carousel v-if="imgArr.length > 0 && !isVisualEditer" height="44px" indicator-position="none" :autoplay="false" arrow="never">
            <px-carousel-item v-for="(iconName, index) in imgArr" :key="index" style="height: 44px">
              <img class="camera" :src="imgMap[iconName]" height="42px" width="32px" @click.stop.self="posEvent(iconName)" />
            </px-carousel-item>
          </px-carousel>
          <Ripple v-else :color="detectColor" :checkDisabled="checkDisabled" :isTriangle="props.propValue.isTriangle" :isFake="isFake" />
        </template>
      </px-tooltip>
    </template>
    <template v-else-if="props.propValue.longDisplay || (isVisualEditer && props.propValue.isEditerlongDisplay)">
      <template v-if="!props.propValue.isCircle">
        <img v-if="isFake" class="pmd-img-disable" src="@/assets/visual/config/drilldisable.png" />
        <img v-else-if="props.propValue.isflowmetre" class="pmd-img" src="@/assets/visual/config/flowmetre.png" />
        <img v-else-if="props.propValue.isvalve" class="pmd-img" src="@/assets/visual/config/valve.png" />
        <img v-else class="pmd-img" src="@/assets/visual/config/drillLocal.png" />
        <div v-if="setDepColor" class="ripple" />
      </template>
      <template v-else>
        <px-carousel v-if="imgArr.length > 0 && !isVisualEditer" height="44px" indicator-position="none" :autoplay="false" arrow="never">
          <px-carousel-item v-for="(iconName, index) in imgArr" :key="index" style="height: 44px">
            <img class="camera" :src="imgMap[iconName]" height="42px" width="32px" @click.stop.self="posEvent(iconName)" />
          </px-carousel-item>
        </px-carousel>
        <Ripple v-else :color="detectColor" :checkDisabled="checkDisabled" :isTriangle="props.propValue.isTriangle" :isFake="isFake" />
      </template>
      <div
        v-show="!attrsTipShow"
        class="drill-tooltip absolute flex items-center justify-center"
        :class="{ 'break-line-wrapper': props.propValue.isBreakLine }"
      >
        <span class="drill-tooltip-inner inline-flex flex-nowrap items-center justify-center" :class="{ 'set-dep-color': setDepColor }">
          <!-- <span :class="{ 'break-line': props.propValue.isBreakLine }">{{ processName }}</span> -->
          <span v-if="current?.type !== 'EQP'" :class="{ 'break-line': props.propValue.isBreakLine }">{{ processName }}</span>
          <div v-else :class="{ 'break-line': props.propValue.isBreakLine }" class="flex flex-col">
            <px-image
              v-show="realImg && !isVisualEditer"
              style="width: 200px; height: 200px"
              :src="realImg"
              :zoom-rate="1.2"
              :initial-index="4"
              :z-index="2000"
              fit="cover"
            />
            <template v-if="props.propValue.groupName">
              <span>
                {{ replaceCharWithNewLine(props.propValue.groupName) }}
              </span>
            </template>
            <template v-else>
              <span class="text-[14px]">编号： {{ current.code }}</span>
              <span class="text-[14px]">名称： {{ current.name }}</span>
            </template>
          </div>
        </span>
      </div>
    </template>
    <!-- <attrsTip
      v-show="attrsTipShow"
      :title="processName"
      :contentList="attrsTipList"
      :curTreeData="flattenTreeData ? flattenTreeData[props.propValue.routerKey] : {}"
    /> -->
  </div>
  <AlertDialog
    v-model:is-show="alertShow"
    :alarmInfo="alarmInfo"
    :group-name="props.propValue.groupName"
    :router-key="props.propValue.routerKey"
    @to-eqp="generalEvent"
  />
  <TableDialog v-model:is-show="tableShow" v-model:group-code="groupCode" />
  <CharlineDialog v-model:is-show="charlineShow" :eqp-id="props.propValue.routerKey" />
  <px-image-viewer v-if="showImagePreview" :zoom-rate="1.2" :z-index="2000" :url-list="imgPreviewList" @close="viewClose" />
</template>
<script setup lang="ts">
import { computed, inject, onBeforeMount, onMounted, ref, watch } from "vue";
import { eventBus } from "@/views/all/visual/template/utils/eventBus";
import { getAssetsFile } from "@visual/utils";
import Ripple from "./ripple.vue";
import TableDialog from "./tableDialog.vue";
import AlertDialog from "../common/alertDialog.vue";
import { routerKey, useRouter } from "vue-router";
import attrsTip from "./attrsTip.vue";
import CharlineDialog from "./charlineDialog.vue";
import NativeTooltip from "../common/NativeTooltip.vue";
import { downloadPic } from "@visual/api/api";

const router = useRouter();

const isVisualEditer = inject("isVisualEditer", false);
const eqpStatusStat = inject("eqpStatusStat", ref([]));
const flattenTreeData = inject("curTreeData", ref({}));
const showAttrsInRoom = inject("showAttrsInRoom", ref({}));
const isInspection = inject("isInspection", ref(""));

const { pipeName } = inject("pipeName", { pipeName: ref() });

const attrsTipList = computed(() => {
  if (flattenTreeData.value) {
    const cur = flattenTreeData.value[props.propValue.routerKey];
    if (cur) {
      const { groupCode } = cur;
      if (groupCode) {
        return showAttrsInRoom.value[groupCode] || [];
      } else {
        return showAttrsInRoom.value[props.propValue.routerKey] || [];
      }
    }
  }
  return [];
});

const tableShow = ref(false);
const alertShow = ref(false);
const charlineShow = ref(false);
const alarmInfo = ref({});
const groupCode = ref("");

const props = withDefaults(
  defineProps<{
    propValue?: {
      title?: string;
      groupName?: string;
      typeId?: null | number;
      tip?: string;
      routerKey?: string;
      routerPath?: string;
      longDisplay?: boolean;
      isCircle?: boolean;
      isEditerlongDisplay?: boolean;
      isPositionRight?: boolean;
      isTriangle?: boolean;
      isBreakLine?: boolean;
      isflowmetre?: boolean;
      isvalve?: boolean;
    };

    remoteData?: { [key: string]: any };
    element?: { [key: string]: any };
  }>(),
  {
    propValue: () => ({
      isEditerlongDisplay: true,
      isPositionRight: true,
      longDisplay: true,
      isTriangle: false,
      isBreakLine: false,
      isflowmetre: false,
      isvalve: false
    })
  }
);
const isFake = computed(() => {
  return !props.propValue.routerKey && !props.propValue.routerPath;
});

const attrsTipShow = computed(() => {
  const cur = flattenTreeData.value[props.propValue.routerKey];
  if (cur && cur["showAttrInRoom"] == 1 && attrsTipList.value.length > 0) return true;
  return false;
});

const emits = defineEmits(["generalEvent"]);
const imglist = ["posalert", "posestop", "posfix", "posinspection", "posmaintian", "posoffline", "poswarn"];
const imgLabel = {
  posalert: "报警", //alarmStatus == 'ON'
  posestop: "待机", //eqpRunStatus == 5
  posfix: "维修", //maintenanceStatus == 3||4
  posinspection: "巡检", //inspectTaskStatus == 2||4
  posmaintian: "保养", //pmsStatus ==  暂无
  posoffline: "离线", //eqpRunStatus == 4
  poswarn: "异常" //eqpRunStatus == 2||3
};
const imgAble = ref({});
const imgMap = {};
const imgArr = ref([]);
let currentTypeName = [];
const { className } = inject("className", { className: ref("") });
const detectColor = ref(null);
const current = ref({});
const realImg = ref("");
const imgPreviewList = ref([]);
const showImagePreview = ref(false);
let timer = null;
watch(current, async () => {
  if (current.value && current.value.realImgName) {
    const res = await downloadPic({ originalName: current.value.realImgName, moduleName: "twins_visualization", moduleId: "9999" });
    if (res && res[0]) {
      const { fileUrl } = res[0];

      realImg.value = fileUrl;
    }
  } else realImg.value = "";
});
eventBus.on("detectChange", id => {
  if (id === props.element.id) {
    detectColor.value = "yellow";
    if (timer) clearTimeout(timer);
    setTimeout(() => {
      detectColor.value = null;
    }, 3000);
  }
});
imglist.forEach(item => {
  imgMap[item] = getAssetsFile(item);
  imgAble.value[item] = item === "posalert" ? true : false;
});
const generalEvent = e => {
  if (isVisualEditer) return;
  if (checkDisabled.value) return;
  //侦测器架台分组弹框
  if (props.propValue.groupName && props.propValue.typeId == 689) {
    tableShow.value = true;
    groupCode.value = props.propValue.groupName;
    return;
  }
  if (e?.target?.toString() == "[object HTMLImageElement]" && e?.target?.className?.indexOf("px-image__inner") !== -1) {
    showImagePreview.value = true;
    imgPreviewList.value = [realImg.value];
    return;
  }
  // const cur = flattenTreeData.value[props.propValue.routerKey];
  // if (cur && cur["showLiquidLevelChange"] == 1 && e?.target?.className?.indexOf("ripple") !== -1) {
  //   charlineShow.value = true;
  //   return;
  // }

  if (props.propValue.routerKey) {
    const next = flattenTreeData.value[props.propValue.routerKey];
    let type = "";
    if (next) {
      type = next.type;
    } else {
      return;
    }
    if (isInspection.value) {
      routerJump("/all/visual/template", { compEmitData: props.propValue.routerKey, type, pipeName: pipeName.value });
      return;
    }
    emits("generalEvent", { type: "compRouter", compEmitData: { compEmitData: props.propValue.routerKey, type, pipeName: pipeName.value } });
  } else if (props.propValue.routerPath) {
    if (isInspection.value) {
      routerJump(props.propValue.routerPath);
      return;
    }
    router.push(props.propValue.routerPath);
  }
};
const viewClose = () => {
  showImagePreview.value = false;
  imgPreviewList.value = [];
};
const posEvent = iconName => {
  if (iconName === "posalert") {
    if (alarmInfo.value) {
      alertShow.value = true;
    }
  } else {
    if (props.propValue.routerKey) {
      const next = flattenTreeData.value[props.propValue.routerKey];
      let type = "";
      if (next) {
        type = next.type;
      } else {
        return;
      }
      emits("generalEvent", { type: "compRouter", compEmitData: { compEmitData: props.propValue.routerKey } });
    } else if (props.propValue.routerPath) {
      router.push(props.propValue.routerPath);
    }
  }
};
const checkDisabled = computed(() => {
  if (isVisualEditer) return false;
  if (eqpStatusStat.value && currentTypeName?.includes("posalert")) return false;
  if (!props.propValue.routerKey && !props.propValue.routerPath) return true;
  if (flattenTreeData.value && props.propValue.routerKey) {
    const curTreeData = flattenTreeData.value[props.propValue.routerKey];
    if (!curTreeData) return true;
  }
  return false;
});
onBeforeMount(() => {
  eventBus.on("posFilterEvent", param => {
    const { rawName, active } = param;
    imgAble.value[rawName] = active;
    imgArr.value = [];
    currentTypeName.forEach(item => {
      if (imgAble.value[item]) {
        imgArr.value.push(item);
      }
    });
  });
});
watch(
  eqpStatusStat,
  () => {
    if (!isObjEmpty(eqpStatusStat.value)) {
      let findStatus = eqpStatusStat.value[props.propValue.routerKey];

      if (props.propValue.groupName) {
        findStatus = eqpStatusStat.value[props.propValue.groupName];
      }
      if (findStatus?.length > 0) {
        findStatus.forEach(el => {
          const { alarmInfo: alarmInfoData, alarmStatus, eqpRunStatus, maintenanceStatus, inspectTaskStatus, pmsStatus } = el;
          if (alarmStatus == "ON") {
            currentTypeName.push("posalert");
            alarmInfo.value = alarmInfoData;
          }
          if (eqpRunStatus == 5) {
            currentTypeName.push("posestop");
          }
          if (maintenanceStatus == 3 || maintenanceStatus == 4) {
            currentTypeName.push("posfix");
          }
          if (inspectTaskStatus == 2 || inspectTaskStatus == 4) {
            currentTypeName.push("posinspection");
          }
          if (eqpRunStatus == 4) {
            currentTypeName.push("posoffline");
          }
          if (eqpRunStatus == 2 || eqpRunStatus == 3) {
            currentTypeName.push("poswarn");
          }
          if (pmsStatus === "ONGONING") {
            currentTypeName.push("posmaintian");
          }
        });
      }
      currentTypeName = [...new Set(currentTypeName)];
      currentTypeName.forEach(item => {
        if (imgAble.value[item]) {
          imgArr.value.push(item);
        }
      });
    }
  },
  {
    immediate: true,
    deep: true
  }
);
const clickRouter = iconName => {
  if (iconName) {
    let jumpePath = null;
    switch (iconName) {
      case "posalert":
        jumpePath = "/all/alert/business"; //报警列表
        break;
      case "posestop":
        jumpePath = "/all/equip/runManage/record";
        break;
      case "posoffline":
        jumpePath = "/all/equip/runManage/record";
        break;
      case "poswarn":
        jumpePath = "/all/equip/runManage/record";
        break;
      case "posfix":
        jumpePath = "/all/equip/maintain/task";
        break;
      case "posinspection":
        jumpePath = "/all/equip/inspect/task"; //
        break;
      case "posmaintian":
        jumpePath = "/all/equip/epm/task/list"; //保养任务列表
        break;
    }
    if (jumpePath) {
      router.push({
        path: jumpePath
      });
    }

    return;
  }
};
function replaceCharWithNewLine(str, charToReplace = ",") {
  if (!str) return str;
  try {
    return str.replace(new RegExp(charToReplace, "g"), "\n");
  } catch (e) {
    return str;
  }
}
watch(
  () => flattenTreeData.value,
  val => {
    if (val) {
      if (props.propValue.routerKey) {
        console.log(props.propValue.routerKey);
        current.value = flattenTreeData.value[props.propValue.routerKey];
      }
    }
  }
);
onMounted(() => {
  if (flattenTreeData.value) {
    if (props.propValue.routerKey) {
      // console.log("onMounted");
      current.value = flattenTreeData.value[props.propValue.routerKey];
    }
  }
});
const setDepColor = computed(() => {
  if (className.value && flattenTreeData.value && props.propValue.routerKey) {
    const curTreeData = flattenTreeData.value[props.propValue.routerKey];
    if (curTreeData) {
      const { className: name } = curTreeData;
      if (name === className.value) return true;
    }
  }
  return false;
});
const processName = computed(() => {
  if (flattenTreeData.value && props.propValue.routerKey) {
    const curTreeData = flattenTreeData.value[props.propValue.routerKey];
    if (curTreeData) {
      const { type, code, className: name } = curTreeData;
      if (type === "EQP") {
        return replaceCharWithNewLine(props.propValue.groupName) || code;
      }
    }
  }
  if (props.propValue.type === "EQP") {
    return replaceCharWithNewLine(props.propValue.groupName || props.propValue.routerKey || props.propValue.tip);
  } else {
    return replaceCharWithNewLine(props.propValue.groupName || props.propValue.tip);
  }
});

function routerJump(path = "", query = {}) {
  const newpage = router.resolve({
    path, // 跳转的页面路由
    query
  });
  window.open(newpage.href, "_blank"); // 打开新的窗口(跳转路径，跳转类型)
}
function openCharline() {
  charlineShow.value = true;
}
function isObjEmpty(obj) {
  // 排除非对象和 null
  if (obj === null || typeof obj !== "object") return true;

  // 优先用 Object.keys（性能最优）
  if (Object.keys(obj).length !== 0) return false;

  // 补充检查 Symbol 和不可枚举属性
  return Object.getOwnPropertySymbols(obj).length === 0 && Object.getOwnPropertyNames(obj).length === 0;
}
</script>
<style lang="scss" scoped>
.loc-point-mark {
  user-select: none;
  transform-origin: 0 0;
}

.pmd-img {
  width: 100%;
  height: 100%;
  cursor: pointer;
  outline: none;
}

.pmd-img-disable {
  width: 100%;
  height: 100%;
  cursor: not-allowed;
  outline: none;
}

.drill-tooltip {
  top: -32px;
  right: 0;
  left: 50%;
  display: inline-flex;
  flex-wrap: nowrap;
  height: 28px;
  margin: auto;
  font-weight: 400;
  line-height: 16px;
  color: #fff;
  white-space: nowrap;
  cursor: pointer;
  transform: translate(-50%);

  & > span {
    padding: 5px;
    line-height: 18px;
    white-space: nowrap;
    background-color: #000;
    border-radius: 4px;
    box-shadow: 0 2px 16px 0 rgb(0 0 0 / 32%);
  }

  // .tooltipsvg {
  //   display: inline-flex;
  //   align-items: center;
  //   justify-content: center;
  //   // height: 28px;
  //   // border-radius: 4px 0 0 4px;
  // }
}

.pmd-img:hover + .drill-tooltip .drill-tooltip-inner {
  background-color: #3b82f6 !important;
}

.set-dep-color {
  background-color: #3b82f6 !important;
}

.popover-rich-conent {
  width: 100%;
  height: auto;

  &-item {
    display: flex;
    align-items: center;
    justify-content: space-around;
    cursor: pointer;
    border-radius: 8px;
  }

  &-item:hover {
    background-color: #3b82f6;
  }
}

.break-line {
  text-align: center;
  white-space: pre;
}

.break-line-wrapper {
  top: auto !important;
  bottom: 35px !important;
  height: auto !important;
  min-height: 28px;
}

.ripple {
  position: absolute;
  top: 75%;
  left: 50%;
  width: 50px; /* Initial size of the ripple */
  height: 25px;
  background: rgb(59 130 246 / 50%); /* Fading color for ripple */
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: ripple-effect 2s infinite;
}

@keyframes ripple-effect {
  0% {
    opacity: 0.8;
    transform: translate(-50%, -50%) scale(1); /* Start at 12px */
  }

  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(2); /* Grow to 24px */
  }
}
</style>
